package com.spring.web.adminmanage.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spring.web.adminmanage.common.PageResult;
import com.spring.web.adminmanage.entities.User;
import com.spring.web.adminmanage.repository.WebUserDao;
import com.spring.web.adminmanage.service.WebUserService;
import com.spring.web.adminmanage.utils.SwordBCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class WebUserServiceImpl extends BaseServiceImpl<User> implements WebUserService {

	@Autowired
	private WebUserDao userDao;
	@Override
	public PageResult<User> queryPageResult(int pageIndex, int pageSize, User user) {
		PageHelper.startPage(pageIndex, pageSize);
		PageInfo<User> pageinfo = new PageInfo<User>(userDao.queryUserResult(user));
		PageResult<User> pageResult = new PageResult<User>(pageinfo);
		return pageResult;
	}
	@Override
	public void operUser(User user) {
		if(user.getId()!=null) {//修改
			userDao.updateUser(user);
		}else {//新增
			user.setUserpassword(SwordBCrypt.hashpw(user.getUsername()+user.getUserpassword()));//加密
			user.setSysPwd(SwordBCrypt.hashpw(user.getUsername()+user.getUserpassword()));
			userDao.saveUser(user);
		}
	}
	@Override
	public void delUser(User user) {
		userDao.delUser(user);
	}
	@Override
	public void updateUser(User user) {
		user.setSysPwd(SwordBCrypt.hashpw(user.getUsername()+user.getSysPwd()));
		userDao.updateUser(user);
	}
	@Override
	public User getUserById(User user) {
		return userDao.getUserById(user);
	}
	@Override
	public User getUserByUsername(User user) {

		return userDao.getUserByUsername(user);
	}
	@Override
	public Boolean checkUserName(User user){
		if(user.getId()==null) {//新增
			user = userDao.getUserByUsername(user);
			if(user != null) {
				return true;
			}
		}else {//修改
			User userbean = getUserById(user);
			if(!userbean.getUsername().equals(user.getUsername())) {
				user = getUserByUsername(user);
				if(user != null) {
					return true;
				}
			}
		}
		return false;
	}
	
	@Override
	public String resetPwd(User user) {
		user = userDao.getUserById(user);
		int randomPwd = (int)((Math.random()*9+1)*100000);
		user.setSysPwd(SwordBCrypt.hashpw(user.getUsername()+randomPwd));
		userDao.updateUser(user);
		return randomPwd+"";
	}
	@Override
	public List<User> getComUserList(User user) {
		Example example = new Example(User.class);
		example.createCriteria().andCondition("role != ", user.getRole().getId());
		return userDao.selectByExample(example);
	}

	@Override
	public User findUser(User sessionUser) {
		User user = new User();
		user.setId(sessionUser.getId());
		return userDao.selectOne(user);
	}

	@Override
	public void updateUserById(User user) {
		user.setDelFlag("0");
		user.setUpdateAt(new Date());
		userDao.updateByPrimaryKeySelective(user);
	}
}